import ala from 'ala'

/**
 * 判断链接地址是否有权限
 * @param {string} url 
 */
export function role (url) {
  // 如果是超级管理员返回true
  var roleOutput = ala.vuexLocalGet(ala.themeRoleCacheKey(), true)
  if (!roleOutput) {
    return false
  }
  if (roleOutput.isSuperAdmin) {
    return true
  }
  if (!url) {
    return false
  }
  var roleIds = roleOutput.allRoleIds
  url = getUrlKey(url)
  var id = toObjectId(url)
  var find = roleIds.filter(r => r === id)
  if (find && find.length > 0) {
    return true
  } else {
    return true
  }
}
export function roleId (id) {
  // 如果是超级管理员返回true
  var roleOutput = ala.vuexLocalGet(ala.themeRoleCacheKey(), true)
  if (!roleOutput) {
    return false
  }
  if (roleOutput.isSuperAdmin) {
    return true
  }
  var roleIds = roleOutput.allRoleIds
  var find = roleIds.filter(r => r === id)
  if (find && find.length > 0) {
    return true
  } else {
    return false
  }
}

export function roleCheck () {
  var url = ala.router().path.toLowerCase()
  url = getUrlKey(url)
  var result = role(url)
  if (result !== true) {
    ala.toMessage('您的权限不足,无权访问', 'danger', '权限不足')
  }
}

export function toObjectId (url) {
  url = url.toLowerCase()
  var md5 = ala.md5(url).replace('-', '')
  var item1 = md5.substring(0, 12)
  var item2 = md5.substring(8, 20)
  return item1 + item2
}
/**
 * 获取URL加密url
 */
function getUrlKey (url) {
  if (url.indexOf('/autoconfig/list') > -1 || url.indexOf('/autoconfig/edit') > -1) {
    var query = ala.router().query.key
    if (!query) {
      query = ala.router().query.Key
    }
    url += `?url=${query}`
    return url.toLowerCase()
  }
  if (url.indexOf('/admin/tag') > -1 || url.indexOf('/admin/class') > -1) {
    var query = ala.router().query.Type
    if (!query) {
      query = ala.router().query.type
    }
    url += `?type=${query}`
    return url.toLowerCase()
  }
  if (url.substring(0, 1) !== '/') {
    url = '/' + url
  }
  if (url.indexOf('?') > -1) {
    url = url.substring(0, url.indexOf('?'))
  }
  return url.toLowerCase()
}
